﻿using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Anke.SHManage.MSSQLDAL;
using Anke.SHManage.Utility;

namespace Anke.SHManage.Web.Areas.IM.Controllers
{
    public class I_InvoiceApprovalController : Controller
    {
        //
        // GET: /IM/I_InvoiceApproval/

        public ActionResult ApprovalList()
        {
            return View();
        }
        public ActionResult DataLoad()
        {

            //string sortName = Request.Form["sort"];
            //string sortOrder = Request.Form["order"];
            string centerID = Request.Form["zcenterCode"];
            string stationID = Request.Form["StationID"];
            DateTime beginTime = Convert.ToDateTime(Request.Form["zAccidentTimeStart"]);
            DateTime endTime = Convert.ToDateTime(Request.Form["zAccidentTimeEnd"]);
            string personName = Request.Form["personName"]; //2018-12-11 zchs

            int rows = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int page = int.Parse(Request.Form["page"]);

            string sortName = Request.Form["sort"];
            string sortOrder = Request.Form["order"];
            //返回总行数
            int rowCounts = 0;
            //var list = new I_InvoiceApprovalBLL().GetInvoiceApplyList(page, rows, sortName, sortOrder, ref rowCounts, centerID, beginTime, endTime);
            var list = new I_InvoiceApprovalBLL().GetInvoiceApplyList(page, rows, sortName, sortOrder, ref rowCounts, centerID, beginTime, endTime, stationID, personName);
            return Json(new { total = rowCounts, rows = list }, "appliction/json", JsonRequestBehavior.AllowGet);
        }


        #region  新增方法  
        /// <summary>
        /// 新增保存方法，
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveApprovalInfo(I_InvoiceApply info)
        {


            info.ApprovalTime = DateTime.Now;
            info.ApprovalUserName = UserOperateContext.Current.Session_UsrInfo.Name;
            info.ApprovalUserID = UserOperateContext.Current.Session_UsrInfo.WorkCode;
            //info.ApprovalUserName = "张三";
            //info.ApprovalUserID = "0202";
            info.ApprovalState = "已审批";
            int aresult = -1;
            aresult = new I_InvoiceApplyBLL().Modify(info, "ApprovalTime", "ApprovalUserName", "ApprovalUserID", "ApprovalState", "Remark2", "ApprovalCount", "StartNumber", "EndNumber");

            //循环中 以主表 applyID +1 作为字表 的ID
            string tempApplyID = Convert.ToString(info.ApplyID);

            Int64 StartNumber = Convert.ToInt64(info.StartNumber);
            Int64 EndNumber = Convert.ToInt64(info.EndNumber);
            Int64 count = EndNumber - StartNumber + 1;    //一共有多少张发票号
            int listresult = -1;
            if (count > 0)
            {
                listresult = new I_InvoiceApprovalBLL().AddI_InvoiceApprovalList(count, StartNumber, tempApplyID);
            }
            //字表无数量，或申领失败，主表状态变申领中
            if (listresult < 0)
            { 
                info.ApprovalState = "申领中";
                new I_InvoiceApplyBLL().Modify(info,  "ApprovalState");

            }

            if (aresult > 0 && listresult >= 0) //主表存储成功， 子表存储成功才会显示成功

                return Json(new { Result = "OK", Message = "审批信息添加成功！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);

            else
                return Json(new { Result = "Error", Message = "审批信息添加失败！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);


        }
        #endregion


        #region 新增的时候判断是否存在已审批的发票号
        [HttpPost]
        public ActionResult IFExistInvoice()
        {
            string txtStartNumber = Convert.ToString(Request.Form["txtStartNumber"]);
            string txtEndNumber = Convert.ToString(Request.Form["txtEndNumber"]);

            bool results = new I_InvoiceApprovalBLL().IFExistInvoice(txtStartNumber, txtEndNumber);

             return Json(results);


        }

        #endregion

        #region 撤销
        [HttpPost]
        public ActionResult deleteApprovalInfo()
        {
            string deleteRowID = Convert.ToString(Request.Form["deleteRowID"]);
            int re = -1;

            re = new I_InvoiceApprovalBLL().deleteI_InvoiceApproval(deleteRowID);

            
            if (re > 0)

                return Json(new { Result = "OK", Message = "审批信息撤销成功！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);

            else
                return Json(new { Result = "Error", Message = "审批信息撤销失败！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);


        }
        #endregion

        #region 手动销号
        public ActionResult InvoiceClearList()
        {
            return View();
        }

        public ActionResult InvoiceClearLoad()
        {
            DateTime beginTime = Convert.ToDateTime(Request.Form["beginTime"]);
            DateTime endTime = Convert.ToDateTime(Request.Form["endTime"]);
            string clearNumber = Convert.ToString(Request.Form["clearNumber"]);
            int rows = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int page = int.Parse(Request.Form["page"]);
            string sortName = Request.Form["sort"];
            string sortOrder = Request.Form["order"];
            //返回总行数
            int rowCounts = 0;
            var list = new I_InvoiceApprovalBLL().getINClearList(page, rows, sortName, sortOrder, ref rowCounts, clearNumber, beginTime, endTime);
            return Json(new { total = rowCounts, rows = list }, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        //提交销号的内容
        [HttpPost]
        public ActionResult submitINClear()
        {
            string PickName = UserOperateContext.Current.Session_UsrInfo.Name;
            string sDeliveryDetailInfo = Request.Form["DataGridInfo"].ToString();
            List<I_InvoiceApplyClear> relist = JsonHelper.GetJsonInfoBy<List<I_InvoiceApplyClear>>(sDeliveryDetailInfo); //前台传来的从表数据
            int results = 0;
            for (int i = 0; i < relist.Count; i++)
            {
                Guid id = System.Guid.NewGuid();
                relist[i].ID = id;
                relist[i].ClearPerson = PickName;
                relist[i].ClearDate = DateTime.Now;
                //results = new I_InvoiceApplyClearBLL().Add(relist[i]); //新增实体成功则返回1
                //results += results;

                //2019-06-13 plq 手动销号超出2条返回记录失败bug修复
                //results = new I_InvoiceApplyClearBLL().Add(relist[i])每次循环都将results重置为1
                //故results最后为2，超出2条时(results >= relist.Count)判断条件恒不成立
                int count = new I_InvoiceApplyClearBLL().Add(relist[i]);
                results += count; 
                
                //2018-12-11 zch
                if (relist[i] != null && relist[i].ClearNumber != null)
                {
                    new I_InvoiceApprovalBLL().DealUsedInvoiceRecord(relist[i].ClearNumber);
                }

            }
            if (results >= relist.Count)
            {
                return this.JsonResult(Utility.E_JsonResult.OK, "记录成功！", null, null);
            }
            else
            {
                return this.JsonResult(Utility.E_JsonResult.Error, "记录失败！", null, null);
            }
        }

        //
        [HttpPost]
        public ActionResult submitINClearCon()
        {
            string PickName = UserOperateContext.Current.Session_UsrInfo.Name;
            string sDeliveryDetailInfo = Request.Form["DataGridInfo"].ToString();
            List<I_InvoiceApplyClear> rowList = JsonHelper.GetJsonInfoBy<List<I_InvoiceApplyClear>>(sDeliveryDetailInfo); //前台传来的从表数据
            int results = 0;
            string checkMessage = "";
            int checkCount = 0;
            for (int i = 0; i < rowList.Count; i++)
            {
                string startNumber = rowList[i].ClearPerson;
                string endNumber = rowList[i].LinkTaskCode;
                int LinkPatientOrder = (int)rowList[i].LinkPatientOrder;
                if (LinkPatientOrder > 0)
                {
                    int count = Convert.ToInt32(endNumber) - Convert.ToInt32(startNumber) + 1;
                    for (int m = 0; m < count; m++)
                    {
                        Int32 SaveNumber = Convert.ToInt32(startNumber) + m;
                        string SaveNumberStr = Convert.ToString(SaveNumber);
                        I_InvoiceApplyClear iac = new I_InvoiceApplyClear();
                        iac.ID = System.Guid.NewGuid();
                        iac.ClearPerson = PickName;
                        iac.ClearDate = DateTime.Now;
                        iac.ClearNumber = SaveNumberStr;

                        I_InvoiceApplyClear info = new I_InvoiceApplyClearBLL().GetModelWithOutTrace(p => p.ClearNumber == SaveNumberStr);
                        if (info == null || info.ClearNumber == "")
                        {
                            if (new I_InvoiceApplyClearBLL().Add(iac) < 0)
                                results = -1;
                            else
                                results = 1;

                            //2018-12-11 zch
                            if (info != null && info.ClearNumber != null)
                            {
                                new I_InvoiceApprovalBLL().DealUsedInvoiceRecord(info.ClearNumber);
                            }
                        }
                        else
                        {
                            checkMessage = checkMessage + SaveNumberStr + ",";
                            checkCount = checkCount + 1;
                        }
                    }
                }
            }

            if (results >= 0 && checkMessage.Length > 0)
            {
                checkMessage = checkMessage + "\r\n" + "等" + checkCount.ToString() + "个是已销号的，不再保存 ！";
                return this.JsonResult(Utility.E_JsonResult.OK, "记录成功！" + checkMessage, null, null);
            }
            if (results >= 0 && checkMessage.Length == 0)
            {

                return this.JsonResult(Utility.E_JsonResult.OK, "记录成功！", null, null);
            }
            else
            {
                return this.JsonResult(Utility.E_JsonResult.Error, "记录失败！", null, null);
            }
        }

        //删除某行数据
        [HttpPost]
        public ActionResult deleteINClear()
        {
            string deleteRowID = Convert.ToString(Request.Form["deleteRowID"]);
            int re = -1;
            I_InvoiceApplyClear info = new I_InvoiceApplyClear();
            info.ID = new Guid(deleteRowID);
            re = new I_InvoiceApplyClearBLL().Del(info);
            if (re > 0)
                return Json(new { Result = "OK", Message = "撤销成功！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
            else
                return Json(new { Result = "Error", Message = "撤销失败！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
        }

        //检查是否已经有重复的发票号
        [HttpPost]
        public ActionResult checkINRepeat()
        {
            string ClearNumber = Convert.ToString(Request.Form["ClearNumber"]);

            I_InvoiceApplyClear info = new I_InvoiceApplyClear();
            info.ClearNumber = "";
            info = new I_InvoiceApplyClearBLL().GetModelWithOutTrace(p => p.ClearNumber == ClearNumber);
            if (info == null || info.ClearNumber == "")
                return Json(new { Result = "OK", Message = "" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);

            else
                return Json(new { Result = "Error", Message = "此条发票号已经销号了！请删除..." }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);

        }

        #endregion
    }
}
